<template>
    <div id="assets">
        <!--搜索框-->
        <div class="interview-header">
            <el-form ref="searchItem" :model="searchItem" :inline="true"  class="demo-form-inline">
                <el-form-item label="订单编号" class="search-item" prop="loanNo">
                    <el-input v-model="searchItem.loanNo" placeholder="订单编号"></el-input>
                </el-form-item>
                <el-form-item label="借款人" class="search-item" prop="realName">
                    <el-input v-model="searchItem.realName" placeholder="借款人"></el-input>
                </el-form-item>
                <el-form-item label="资产状态" prop="assetStatus">
                    <el-select  v-model.number="searchItem.assetStatus" placeholder="资产状态">
                        <el-option label="待发标" :value=0></el-option>
                        <el-option label="发标待审核" :value=1></el-option>
                        <el-option label="融资中" :value=2></el-option>
                        <el-option label="满标待审" :value=3></el-option>
                        <el-option label="待放款审核" :value=4></el-option>
                        <el-option label="待创建还款" :value=5></el-option>
                        <el-option label="还款中" :value=6></el-option>
                        <el-option label="已还款" :value=7></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="fa-search" @click="loadData">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button icon="fa-repeat" @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!--列表-->
        <div class="table-box">
            <div class="export-btn">
                <el-button type="primary" @click="export2Excel">导出</el-button>
            </div>

            <el-table border :data="tableData"  @selection-change="handleSelectionChange">
                <el-table-column type="selection" align="center" width="55"></el-table-column>
                <el-table-column type="index" align="center" label="序号" width="70"></el-table-column>
                <el-table-column prop="assetStatus" align="center" label="状态" width="140"></el-table-column>
                <el-table-column show-overflow-tooltip align="center" label="订单编号" width="200">
                    <template scope="scope">
                        <router-link :to="{path: '/apply/borrowerDetails', query: {loanNo: scope.row.loanNo, userNo: scope.row.userNo}}" style="color: #20a0ff"><span>{{scope.row.loanNo}}</span></router-link>
                    </template>
                </el-table-column>
                <el-table-column prop="realName" align="center" label="借款人" width="110"></el-table-column>
                <el-table-column prop="beginTime" align="center" label="借款时间" width="190"></el-table-column>
                <el-table-column prop="loanAmount" align="center" label="借款金额（元）" width="160"></el-table-column>
                <el-table-column prop="loanTime" align="center" label="借款期限" width="100"></el-table-column>
                <el-table-column prop="interestRate" align="center" label="综合利率（%）" width="160"></el-table-column>
                <el-table-column prop="repayType" align="center" label="还款方式" width="100"></el-table-column>
                <el-table-column prop="interest" align="center" label="利息总额（元）" width="160"></el-table-column>
                <el-table-column prop="allAmount" align="center" label="借款本息总额（元）" width="220"></el-table-column>
                <el-table-column prop="repayedAmount" align="center" label="已还总额（元）" width="200"></el-table-column>
                <el-table-column prop="repayedCount" align="center" label="已还期数" width="120"></el-table-column>
                <el-table-column prop="lessAmount" align="center" label="剩余未还总额（元）" width="180"></el-table-column>
                <el-table-column prop="overdueAmount" align="center" label="逾期金额（元）" width="160"></el-table-column>
                <el-table-column prop="overdueInterest" align="center" label="逾期利息（元）" width="160"></el-table-column>
                <el-table-column prop="matchPlan" align="center" label="匹配编号（理财计划编号）" width="220"></el-table-column>
                <el-table-column prop="matchTime" align="center" label="匹配时间" width="190"></el-table-column>
                <el-table-column prop="outAmount" align="center" label="放款金额（元）" width="160"></el-table-column>
                <el-table-column prop="outTime" align="center" label="放款时间" width="190"></el-table-column>
                <el-table-column prop="operatorNo" align="center" label="操作人" width="150"></el-table-column>
                <el-table-column align="" label="操作" fixed="right" width="180">
                    <template scope="scope">
                        <el-button size="small">
                            <a :href="baseURL + '/api-loan/loan/download/loanFile?platformNo=1&loanNo=' + scope.row.loanNo" download="文件下载" style="text-decoration: none;color: #1f2d3d;">下载</a>
                        </el-button>
                        <el-button type="primary" size="small" v-if="scope.row.assetStatus === '待发标'" @click="Marking(scope.row)">发标</el-button>
                        <el-button size="small" type="primary" v-if="scope.row.assetStatus === '发标待审核'" @click="AuditOpen(scope.row)">审核</el-button>
                        <el-button size="small" type="primary" v-if="scope.row.assetStatus === '融资中'" @click="sorryDialog = true">暂停</el-button>
                        <el-button size="small" type="primary" v-if="scope.row.assetStatus === '满标待审'" @click="AuditOpen(scope.row)">审核</el-button>
                        <el-button size="small" type="primary" v-if="scope.row.assetStatus === '待放款审核'" @click="submitOut(scope.row)">确认放款</el-button>
                        <el-button size="small" type="primary" v-if="scope.row.assetStatus === '待创建还款'" @click="openCreateRepay(scope.row)">创建还款</el-button>
                        <el-button size="small" type="primary" v-if="scope.row.assetStatus === '还款中'" @click="sorryDialog = true">还款</el-button>
                        <el-button size="small" type="primary" v-if="scope.row.assetStatus === '已还款'" @click="ViewDetails(scope.row)">查看详情</el-button>
                    </template>
                </el-table-column>

            </el-table>
        </div>

        <!--分页-->
        <div class="pageNum">
            <el-pagination
                @current-change ="handleCurrentChange"
                @size-change="handleSizeChange"
                :pageNum-sizes="pagesize"
                layout="prev, pager, next, total, sizes"
                :total="total">
            </el-pagination>
        </div>

        <!--发标审核-->
        <el-dialog title="发标审核" :visible.sync="dialogBidAudit" class="dialog">
            <el-form :model="BidAuditInfo" ref="BidAuditInfo" class="el-form" :inline="true" labelWidth="80px">
                <el-form-item label="是否通过" prop="checkStatus" required>
                    <el-radio-group v-model.number="BidAuditInfo.checkStatus">
                        <el-radio :label=1>通过</el-radio>
                        <el-radio :label=0>不通过</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <el-form :model="BidAuditInfo" label-width="80px" :rules="rulesDialog">
                <el-form-item label="审核说明" prop="checkInfo">
                    <el-input type="textarea" v-model="BidAuditInfo.checkInfo" :rows="5" style="width: 473px;" resize="none"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogBidAudit = false">取 消</el-button>
                <el-button type="primary" @click="AuditPass()">确 定</el-button>
            </div>
        </el-dialog>

        <!--暂停功能暂不支持-->
        <el-dialog title="抱歉" :visible.sync="sorryDialog" class="dialog">
            <p>此功能暂不支持，敬请期待！</p>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="sorryDialog = false">确 定</el-button>
            </div>
        </el-dialog>

        <!--创建还款-->
        <el-dialog title="创建还款" :visible.sync="dialogCreateRepay" class="dialog" :before-close="closeCreateRepay">
            <el-form :model="CreateRepayInfo" label-width="120px" :rules="rulesDialog" ref="CreateRepayInfo">
                <el-form-item label="还款起始时间" prop="beginTime">
                    <el-date-picker
                        v-model="CreateRepayInfo.beginTime"
                        type="datetime"
                        :editable="false"
                        placeholder="选择日期时间"
                        align="right"
                        :default-value="CreateRepayInfo.beginTime"
                    >
                    </el-date-picker>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closeCreateRepay()">取 消</el-button>
                <el-button type="primary" @click="postCreateRepay()">确 定</el-button>
            </div>
        </el-dialog>

        <a id="downloadA"></a>

    </div>
</template>

<script>
    import { listLoanAsset, createCheck, exportAsset, out, createRepay, loanFileDownload, returnLoanCheck } from "@/api/api";
    export default {
        name: "assets",
        data () {
            return {
                total: 0,
                pagesize: ["10","30","50"],
                searchItem: {
                    loanNo: "",
                    realName: "",
                    assetStatus: "",
                    pageNum: 1,
                    pageSize: 10
                },
                exportItem: {
                    loanNo: "",
                    realName: "",
                    assetStatus: ""
                },
                tableData: [],
                multipleSelection: [],
                // 发表审核弹窗框；
                dialogBidAudit: false,
                // 暂停；
                sorryDialog: false,
                BidAuditInfo: {
                    loanNo: "",
                    checkStatus: 1,
                    checkInfo: ""
                },
                rulesDialog: {
                    beginTime: [
                        { type: 'date', required: true, message: '请输入还款起始时间', trigger: 'change' }
                    ]
                },
                // 创建还款
                dialogCreateRepay: false,
                CreateRepayInfo: {
                    loanNo: "",
                    beginTime: new Date()
                },
                hrefUrl: "",
                baseURL: process.env.API_URL
            };
        },
        mounted: function () {
            this.$nextTick(function () {
                this.loadData();
            });
        },
        watch: {
            $route (to) {
                if(to.name === "asset"){
                    this.loadData();
                    window.sessionStorage.removeItem("createLoan");
                }
            }
        },
        methods: {
            // 重置
            resetForm () {
                this.$refs.searchItem.resetFields();
            },
            // 选中
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 导出
            export2Excel() {
                require.ensure([], () => {
                    const { export_json_to_excel } = require('../../vendor/Export2Excel');
                    const tHeader = ['状态', '订单编号', '借款人', '借款时间', '借款金额', '借款期限', '综合利率', '还款方式', '利息总额', '借款本息总额', '已还总额', '已还期数', '剩余未还总额', '逾期金额', '逾期利息', '匹配编号（理财计划编号）', '匹配时间', '放款金额', '放款时间', '操作人']; // 对应表格输出的title
                    const filterVal = ['assetStatus', 'loanNo', 'realName', 'beginTime', 'loanAmount', 'loanTime', 'interestRate', 'repayType', 'interest', 'allAmount', 'repayedAmount', 'repayedCount', 'lessAmount', 'overdueAmount', 'overdueInterest', 'matchPlan', 'matchTime', 'outAmount', 'outTime', 'operatorNo']; // 对应表格输出的数据
                    const list = this.multipleSelection;
                    const data = this.formatJson(filterVal, list);
                    if (list.length > 0) {
                        export_json_to_excel(tHeader, data, '资产管理列表excel'); // 对应下载文件的名字
                    } else {
                        this.$message({
                            message: "请选择需要导出的数据",
                            type: 'error'
                        });
                    }
                });
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]));
            },
            // 资产管理列表、查询
            async loadData () {
                let _this = this;
                await listLoanAsset(this.searchItem).then(function(res) {
                    let Data = JSON.parse(res.data.ciphertext);
                    if (Data) {
                        _this.tableData = Data.list;
                        console.log(_this.tableData);
                        _this.total = Data.total;
                        let arr = _this.tableData;
                        for (let i=0; i<arr.length; i++) {
                            let assetStatusArr = ["待发标", "发标待审核", "融资中", "满标待审", "待放款审核", "待创建还款", "还款中", "已还款"];
                            let DateUnit = ["年", "月", "日"];
                            let signRepayType = ["到期还款", "先息后本", "等额本息", "等额本金"];
                            // 状态
                            arr[i].assetStatus = assetStatusArr[arr[i].assetStatus];

                            // 还款方式
                            arr[i].repayType = signRepayType[arr[i].repayType];

                            // 借款期限// 申请期限
                            arr[i].loanTime = arr[i].loanTime + DateUnit[arr[i].loanUnit];

                            // 借款时间
                            if (arr[i].beginTime) {
                                arr[i].beginTime = _this.formatTime(arr[i].beginTime);
                            }
                            // 放款时间
                            if (arr[i].outTime) {
                                arr[i].outTime = _this.formatTime(arr[i].outTime);
                            }

                            // 面签时间
                            if (arr[i].signTime) {
                                arr[i].signTime = _this.formatTime(arr[i].signTime);
                            }

                            // 还款方式
                            arr[i].signRepayType = signRepayType[arr[i].signRepayType];
                        };
                    }
                });
            },
            // 审核通过打开
            AuditOpen (rows) {
                this.dialogBidAudit =true;
                this.BidAuditInfo.loanNo = rows.loanNo;
            },
            // 审核通过、审核不通过；
            async AuditPass () {
                let _this = this;
                await createCheck(this.BidAuditInfo).then((res) => {
                    if (res.data.state.code === "200") {
                        _this.$message({
                            message: "成功",
                            type: 'success'
                        });
                        this.dialogBidAudit = false;
                        _this.loadData();
                        _this.BidAuditInfo.checkInfo = "";
                    } else {
                        _this.$message({
                            message: res.data.state.message,
                            type: 'error'
                        });
                    }
                });
            },
            // 放款
            submitOut (rows) {
                this.$confirm('是否放款?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.postOut(rows);
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消放款'
                    });
                });
            },
            async postOut (rows) {
                let _this = this;
                await out({
                    "loanNo": rows.loanNo
                }).then((res) => {
                    if(res.data.state.code === "200"){
                        _this.$message({
                            message: '成功',
                            type: 'success'
                        });
                    }
                });
            },
            // 创建还款
            openCreateRepay (rows) {
                this.dialogCreateRepay = true;
                this.CreateRepayInfo.loanNo = rows.loanNo;
            },
            closeCreateRepay () {
                this.dialogCreateRepay = false;
                this.CreateRepayInfo.beginTime = new Date();
                this.$refs.CreateRepayInfo.resetFields();
            },
            postCreateRepay () {
                let _this = this;
                this.$refs.CreateRepayInfo.validate((valid) => {
                    if (valid) {
                        createRepay(this.CreateRepayInfo).then((res) => {
                            if(res.data.state.code === "200"){
                                _this.$message({
                                    message: '成功',
                                    type: 'success'
                                });
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            // 发标
            Marking (rows) {
                this.$router.push({path: '/asset/assetsMarkOne', query: { loanNo: rows.loanNo }});
            },
            // 查看；
            ViewDetails (rows) {
                this.$router.push({path: '/apply/borrowerDetails', query: {loanNo: rows.loanNo, userNo: rows.userNo}});
            },
            // 当前页码
            handleCurrentChange(val){
                this.searchItem.pageNum = val;
                this.loadData();
            },
            // 每页条数;
            handleSizeChange(val){
                this.searchItem.pageSize = val;
                this.loadData();
            }
        }
    };
</script>

<style lang="scss">
  #assets{
      .interview-header{
          border: 1px solid #eee;
          margin:20px;
          padding:22px 0 0 20px;
          min-width: 1200px;
          box-sizing: border-box;
          .search-in{
              .search-item{
                  margin-right: 30px;
              }
          }
      }
      .table-box{
          border: 1px solid #eee;
          margin:20px;
          min-width: 1200px;
          .add-btn{
              margin: 20px;
              .el-icon-plus{
                  font-size:12px;
              }
          }
          .export-btn{
            padding: 15px;
          }
      }
      .pageNum{
          text-align: right;
          padding: 0 10px;
          .el-pagination{
              padding:0;
          }
      }
      .dialog{
          .el-form {
              width: 564px;
              margin: 0 auto;
          }
      }
  }
</style>
